



#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include "font.h"
#include "lv_draw.h"
#include "touch.h"
#include <time.h>
#include <sys/time.h>
#include <linux/input.h>

// 前置声明
int preload_images(void);
void free_images(void);
void show_calendar(void);
void show_weather(void);
void show_notice(void);
int login(void);
void start_game();
void turn_on();
void show_poem();
volatile int run_chinese = 0;
#define NUM_PICS 5
int current_pic_index          = 0;
volatile int calendar_launched = 0;
volatile int weather_launched  = 0;
volatile int notice_launched   = 0;
volatile int game_launched     = 0;

// 全局图标重绘标志
volatile int need_redraw_icons = 1;

int x, y;

Image images[NUM_PICS];

// 广告区域双缓冲
#define AD_WIDTH 600
#define AD_HEIGHT 360
unsigned int ad_buffer[AD_WIDTH * AD_HEIGHT];

// 预加载图片到内存
int preload_images()
{
    const char * paths[NUM_PICS] = {"/picture/milk.bmp", "/picture/tv.bmp", "/picture/lock.bmp", "/picture/fans.bmp",
                                    "/picture/sofa.bmp"};

    for(int i = 0; i < NUM_PICS; i++) {
        if(lv_draw_paint_bmp_to_memory(paths[i], &images[i]) < 0) {
            printf("预加载图片失败: %s\n", paths[i]);
            continue;
        }

        int width               = images[i].width;
        int height              = images[i].height;
        unsigned int * data     = images[i].data;
        unsigned int * temp_buf = (unsigned int *)malloc(width * height * sizeof(unsigned int));
        if(!temp_buf) {
            printf("内存分配失败\n");
            continue;
        }

        for(int row = 0; row < height; row++) {
            for(int col = 0; col < width; col++) {
                temp_buf[row * width + col] = data[(height - 1 - row) * width + col];
            }
        }

        memcpy(data, temp_buf, width * height * sizeof(unsigned int));
        free(temp_buf);
    }
    return 0;
}

// 释放图片内存
void free_images()
{
    for(int i = 0; i < NUM_PICS; i++) {
        if(images[i].data) {
            free(images[i].data);
            images[i].data = NULL;
        }
    }
}

// 主界面触摸处理线程
void * main_touch_thread(void * arg)
{
    int touch_fd = open("/dev/input/event0", O_RDONLY);
    if(touch_fd == -1) {
        perror("open touch device failed");
        return NULL;
    }

    struct input_event event;
    int x = 0, y = 0;
    volatile int touch_x = -1, touch_y = -1;
    volatile int touch_release = 0;

    while(run_chinese == 1) {
        if(read(touch_fd, &event, sizeof(event)) != sizeof(event)) {
            perror("read touch event failed");
            continue;
        }

        if(event.type == EV_ABS) {
            if(event.code == ABS_X) {
                x = event.value * 800 / 1024;
            } else if(event.code == ABS_Y) {
                y = event.value * 480 / 600;
            }
        }

        if(event.type == EV_KEY && event.code == BTN_TOUCH) {
            if(event.value == 1) {
                touch_x = x;
                touch_y = y;
            } else if(event.value == 0) {
                if(touch_x != -1 && touch_y != -1) {
                    touch_release = 1;
                    if(touch_x >= 10 && touch_x <= 110 && touch_y >= 380 && touch_y <= 480) {
                        calendar_launched = 1;
                        run_chinese       = 0;
                    } else if(touch_x >= 10 && touch_x <= 110 && touch_y >= 20 && touch_y <= 120) {
                        notice_launched = 1;
                        run_chinese     = 0;
                    } else if(touch_x >= 10 && touch_x <= 110 && touch_y >= 260 && touch_y <= 360) {
                        weather_launched = 1;
                        run_chinese      = 0;
                    } else if(touch_x >= 10 && touch_x <= 110 && touch_y >= 140 && touch_y <= 240) {
                        game_launched = 1;
                        run_chinese   = 0;
                    }
                }
            }
        }
        usleep(10000);
    }

    close(touch_fd);
    return NULL;
}

void show_poem()
{
    FILE * file = fopen("poem.txt", "r");
    if(!file) {
        printf("File open failed");
        return;
    }
    lv_draw_string_bmp("初夏即事", 45, 5, RGB(0, 0, 0), 28);
    lv_draw_string_bmp("北宋 王安石", 20, 40, RGB(0, 0, 0), 28);
    char buffer[1024];
    int y_offset          = 75;
    const int line_height = 35;

    while(fgets(buffer, sizeof(buffer), file)) {
        char * token = strtok(buffer, "n");
        while(token) {
            lv_draw_string_bmp(token, 0, y_offset, 0x000000, 28);
            y_offset += line_height;
            token = strtok(NULL, "n");
        }
    }
    fclose(file);
}

// 显示天气界面
void show_weather()
{
    lv_draw_paint_bmp("/picture/big_wheater.bmp", 0, 0);
    show_poem();
    int touch_fd = open("/dev/input/event0", O_RDONLY);
    if(touch_fd == -1) {
        perror("open touch device failed");
        return;
    }

    struct input_event event;
    int x = 0, y = 0;
    int touch_x = -1, touch_y = -1;

    while(weather_launched) {
        if(read(touch_fd, &event, sizeof(event)) != sizeof(event)) {
            perror("read touch event failed");
            continue;
        }

        if(event.type == EV_ABS) {
            if(event.code == ABS_X) {
                x = event.value * 800 / 1024;
            } else if(event.code == ABS_Y) {
                y = event.value * 480 / 600;
            }
        }

        if(event.type == EV_KEY && event.code == BTN_TOUCH) {
            if(event.value == 1) {
                touch_x = x;
                touch_y = y;
            } else if(event.value == 0) {
                if(touch_x != -1 && touch_y != -1) {
                    weather_launched = 0;
                }
            }
        }
        usleep(10000);
    }

    close(touch_fd);
    lv_fill_clean_bmp(0, 0, 800, 480, RGB(255, 255, 255));
}

// 显示公告界面
void show_notice()
{
    lv_draw_paint_bmp("/picture/big_notice.bmp", 0, 0);
    int touch_fd = open("/dev/input/event0", O_RDONLY);
    if(touch_fd == -1) {
        perror("open touch device failed");
        return;
    }

    struct input_event event;
    int x = 0, y = 0;
    int touch_x = -1, touch_y = -1;

    while(notice_launched) {
        if(read(touch_fd, &event, sizeof(event)) != sizeof(event)) {
            perror("read touch event failed");
            continue;
        }

        if(event.type == EV_ABS) {
            if(event.code == ABS_X) {
                x = event.value * 800 / 1024;
            } else if(event.code == ABS_Y) {
                y = event.value * 480 / 600;
            }
        }

        if(event.type == EV_KEY && event.code == BTN_TOUCH) {
            if(event.value == 1) {
                touch_x = x;
                touch_y = y;
            } else if(event.value == 0) {
                if(touch_x != -1 && touch_y != -1) {
                    notice_launched = 0;
                }
            }
        }
        usleep(10000);
    }

    close(touch_fd);
    lv_fill_clean_bmp(0, 0, 800, 480, RGB(255, 255, 255));
}

// 关键优化：广告显示函数
void refresh_ad_immediately()
{
    for(int i = 0; i < AD_WIDTH * AD_HEIGHT; i++) {
        ad_buffer[i] = RGB(255, 255, 255);
    }

    Image * img = &images[current_pic_index];
    if(img->data) {
        int width   = (img->width > AD_WIDTH) ? AD_WIDTH : img->width;
        int height  = (img->height > AD_HEIGHT) ? AD_HEIGHT : img->height;
        int start_x = (AD_WIDTH - width) / 2;
        int start_y = (AD_HEIGHT - height) / 2;

        for(int y = 0; y < height; y++) {
            for(int x = 0; x < width; x++) {
                int buf_x = start_x + x;
                int buf_y = start_y + y;

                if(buf_x >= 0 && buf_x < AD_WIDTH && buf_y >= 0 && buf_y < AD_HEIGHT) {
                    ad_buffer[buf_y * AD_WIDTH + buf_x] = img->data[y * img->width + x];
                }
            }
        }
    }

    int ad_start_x = (800 - AD_WIDTH) / 2;
    int ad_start_y = (480 - AD_HEIGHT) / 2;

    for(int y = 0; y < AD_HEIGHT; y++) {
        for(int x = 0; x < AD_WIDTH; x++) {
            lv__reak_draw_point(ad_start_x + x, ad_start_y + y, ad_buffer[y * AD_WIDTH + x]);
        }
    }
}

int show_chinese()
{
    pthread_t touch_tid;
    time_t last_local_pic_update = 0;

    while(1) {
        if(run_chinese == 0) {
            usleep(100000);
            need_redraw_icons = 1;
        } else if(run_chinese == 1) {
            if(pthread_create(&touch_tid, NULL, main_touch_thread, NULL) != 0) {
                perror("创建主界面触摸线程失败");
                continue;
            }

            // 图标绘制代码保持不变
            lv_fill_clean_bmp(10, 20, 100, 100, RGB(255, 255, 255));
            lv_draw_paint_bmp("/picture/notice.bmp", 10, 20);

            lv_fill_clean_bmp(10, 260, 100, 100, RGB(255, 255, 255));
            lv_draw_paint_bmp("/picture/wheater.bmp", 10, 260);

            lv_fill_clean_bmp(10, 380, 100, 100, RGB(255, 255, 255));
            lv_draw_paint_bmp("/picture/calendar.bmp", 10, 380);

            lv_fill_clean_bmp(10, 140, 100, 100, RGB(255, 255, 255));
            lv_draw_paint_bmp("/picture/game.bmp", 10, 140);

            // 立即刷新广告并重置计时器
            refresh_ad_immediately();
            last_local_pic_update = time(NULL);
            need_redraw_icons     = 0;

            char buf[64]            = {0};
            unsigned int font_size  = 36;
            int display_x           = 100;
            int display_y           = 0;
            int notice_x            = 100;
            int notice_y            = 440;
            char notice_path[]      = "notice.txt";
            time_t last_time_update = 0;

            FILE * notice_file          = fopen(notice_path, "r");
            char notice_lines[100][256] = {{0}};
            int line_count              = 0;
            int notice_index            = 0;
            unsigned int notice_font    = 36;
            time_t last_notice_change   = 0;

            if(notice_file) {
                char temp[1024];
                while(fgets(temp, sizeof(temp), notice_file) && line_count < 100) {
                    char * token = strtok(temp, "n");
                    while(token != NULL && line_count < 100) {
                        token[strcspn(token, "n")] = 0;
                        if(strlen(token) > 0) {
                            strncpy(notice_lines[line_count], token, sizeof(notice_lines[0]) - 1);
                            line_count++;
                        }
                        token = strtok(NULL, "n");
                    }
                }
                fclose(notice_file);
            } else {
                printf("无公告文件，使用默认公告\n");
                strcpy(notice_lines[0], "暂无小区公告");
                line_count = 1;
            }

            unsigned int time_color_buf[800 * 40];
            unsigned int * p = time_color_buf;
            for(y = 0; y < font_size; y++) {
                for(x = 100; x < LCD_WIDTH; x++) {
                    *p = lv_reader_point(x, y);
                    p++;
                }
            }

            unsigned int notice_color_buf[800 * 40];
            unsigned int * notice_p = notice_color_buf;
            for(y = notice_y; y < notice_y + notice_font; y++) {
                for(x = notice_x; x < LCD_WIDTH; x++) {
                    *notice_p = lv_reader_point(x, y);
                    notice_p++;
                }
            }

            while(run_chinese == 1) {
                time_t now           = time(NULL);
                struct tm * sys_time = localtime(&now);

                if(now - last_time_update >= 1) {
                    last_time_update = now;
                    sprintf(buf, "%04d年%02d月%02d日 %02d时%02d分%02d秒 天气：晴", sys_time->tm_year + 1900,
                            sys_time->tm_mon + 1, sys_time->tm_mday, sys_time->tm_hour, sys_time->tm_min,
                            sys_time->tm_sec);

                    p = time_color_buf;
                    for(y = 0; y < font_size; y++) {
                        for(x = 100; x < LCD_WIDTH; x++) {
                            lv__reak_draw_point(x, y, *p);
                            p++;
                        }
                    }
                    lv_draw_string_bmp(buf, display_x, display_y, RGB(255, 0, 0), font_size);
                }

                // 使用局部计时器判断广告切换
                if(now - last_local_pic_update >= 6) {
                    last_local_pic_update = now;
                    refresh_ad_immediately();
                    current_pic_index = (current_pic_index + 1) % NUM_PICS;
                }

                if(now - last_notice_change >= 3) {
                    last_notice_change = now;
                    notice_p           = notice_color_buf;
                    for(y = notice_y; y < notice_y + notice_font; y++) {
                        for(x = notice_x; x < LCD_WIDTH; x++) {
                            lv__reak_draw_point(x, y, *notice_p);
                            notice_p++;
                        }
                    }
                    notice_index = (notice_index + 1) % line_count;
                    lv_draw_string_bmp(notice_lines[notice_index], notice_x, notice_y, RGB(255, 0, 0), notice_font);
                }
                usleep(950000);
            }
            pthread_cancel(touch_tid);
            pthread_join(touch_tid, NULL);
        }
    }
    return 0;
}

// 游戏启动函数
void start_game()
{
    int lcd = open("/dev/fb0", O_RDWR);
    if(lcd < 0) {
        perror("open lcd failed");
        return;
    }
    turn_on();
    close(lcd);
}

// 关键改进：在界面切换后立即重绘图标
int lcd_inter_face()
{
    if(lcd_open("/dev/fb0") < 0) {
        perror("LCD初始化失败");
        return 1;
    }
    lv_clear_fill(RGB(255, 255, 255));

    if(lv_font_select_chinese("./simkai.ttf") < 0) {
        printf("字体加载失败\n");
        lv_close();
        return 1;
    }

    if(preload_images() < 0) {
        lv_close();
        return -1;
    }

    pthread_t login_thread, chinese_thread;

    if(pthread_create(&login_thread, NULL, (void *)login, NULL) != 0) {
        perror("创建登录线程失败");
        return 1;
    }

    if(pthread_create(&chinese_thread, NULL, (void *)show_chinese, NULL) != 0) {
        perror("创建主界面线程失败");
        return 1;
    }

    while(1) {
        if(calendar_launched) {
            calendar_launched = 0;
            show_calendar();
            lv_fill_clean_bmp(0, 0, 800, 480, RGB(255, 255, 255));
            run_chinese       = 1;
            need_redraw_icons = 1;
            
            // 立即重绘四个小图标
            lv_fill_clean_bmp(10, 20, 100, 100, RGB(255, 255, 255));
            lv_draw_paint_bmp("/picture/notice.bmp", 10, 20);
            lv_fill_clean_bmp(10, 260, 100, 100, RGB(255, 255, 255));
            lv_draw_paint_bmp("/picture/wheater.bmp", 10, 260);
            lv_fill_clean_bmp(10, 380, 100, 100, RGB(255, 255, 255));
            lv_draw_paint_bmp("/picture/calendar.bmp", 10, 380);
            lv_fill_clean_bmp(10, 140, 100, 100, RGB(255, 255, 255));
            lv_draw_paint_bmp("/picture/game.bmp", 10, 140);
            
        } else if(weather_launched) {
            show_weather();
            lv_fill_clean_bmp(0, 0, 800, 480, RGB(255, 255, 255));
            run_chinese       = 1;
            need_redraw_icons = 1;
            
            // 立即重绘四个小图标
            lv_fill_clean_bmp(10, 20, 100, 100, RGB(255, 255, 255));
            lv_draw_paint_bmp("/picture/notice.bmp", 10, 20);
            lv_fill_clean_bmp(10, 260, 100, 100, RGB(255, 255, 255));
            lv_draw_paint_bmp("/picture/wheater.bmp", 10, 260);
            lv_fill_clean_bmp(10, 380, 100, 100, RGB(255, 255, 255));
            lv_draw_paint_bmp("/picture/calendar.bmp", 10, 380);
            lv_fill_clean_bmp(10, 140, 100, 100, RGB(255, 255, 255));
            lv_draw_paint_bmp("/picture/game.bmp", 10, 140);
            
        } else if(notice_launched) {
            show_notice();
            lv_fill_clean_bmp(0, 0, 800, 480, RGB(255, 255, 255));
            run_chinese       = 1;
            need_redraw_icons = 1;
            
            // 立即重绘四个小图标
            lv_fill_clean_bmp(10, 20, 100, 100, RGB(255, 255, 255));
            lv_draw_paint_bmp("/picture/notice.bmp", 10, 20);
            lv_fill_clean_bmp(10, 260, 100, 100, RGB(255, 255, 255));
            lv_draw_paint_bmp("/picture/wheater.bmp", 10, 260);
            lv_fill_clean_bmp(10, 380, 100, 100, RGB(255, 255, 255));
            lv_draw_paint_bmp("/picture/calendar.bmp", 10, 380);
            lv_fill_clean_bmp(10, 140, 100, 100, RGB(255, 255, 255));
            lv_draw_paint_bmp("/picture/game.bmp", 10, 140);
            
        } else if(game_launched) {
            game_launched = 0;
            lv_fill_clean_bmp(0, 0, 800, 480, RGB(255, 255, 255));
            lv_draw_paint_bmp("/picture/2048.bmp", 0, 0);
            sleep(1);
            lv_fill_clean_bmp(0, 0, 800, 480, RGB(255, 255, 255));
            lv_draw_paint_bmp("/picture/hand.bmp", 0, 0);
            sleep(6);
            start_game();
            lv_fill_clean_bmp(0, 0, 800, 480, RGB(255, 255, 255));
            run_chinese       = 1;
            need_redraw_icons = 1;
            
            // 立即重绘四个小图标
            lv_fill_clean_bmp(10, 20, 100, 100, RGB(255, 255, 255));
            lv_draw_paint_bmp("/picture/notice.bmp", 10, 20);
            lv_fill_clean_bmp(10, 260, 100, 100, RGB(255, 255, 255));
            lv_draw_paint_bmp("/picture/wheater.bmp", 10, 260);
            lv_fill_clean_bmp(10, 380, 100, 100, RGB(255, 255, 255));
            lv_draw_paint_bmp("/picture/calendar.bmp", 10, 380);
            lv_fill_clean_bmp(10, 140, 100, 100, RGB(255, 255, 255));
            lv_draw_paint_bmp("/picture/game.bmp", 10, 140);
        }
        usleep(100000);
    }

    pthread_join(login_thread, NULL);
    pthread_join(chinese_thread, NULL);

    free_images();
    lv_close();
    return 0;
}